package com.lindroy.todomvp.addtask

import android.app.ActivityManager
import com.lindroy.todomvp.data.Task
import com.lindroy.todomvp.data.source.TasksDataSource

/**
 * @author Lin
 * @date 2021/6/25
 * @function
 */
class AddEditTaskPresenter(
    private val taskId: String?,
    val tasksRepository: TasksDataSource,
    val addTaskView: AddEditTaskContract.View,
    override var isDataMissing: Boolean
):AddEditTaskContract.Presenter,TasksDataSource.GetTaskCallback{

    init {
        addTaskView.presenter = this
    }

    override fun saveTask(title: String, description: String) {
        if (taskId == null){
            createTask(title,description)
        }else{
            updateTask(title, description)
        }
    }

    override fun populateTask() {

    }

    override fun start() {

    }

    override fun onTaskLoaded(task: Task) {

    }

    override fun onDataNotAvailable() {
    }


    private fun createTask(title: String,desc:String){
        val newTask = Task(title,desc)
        if (newTask.isEmpty){
            addTaskView.showEmptyTaskError()
        }else{
            tasksRepository.saveTask(newTask)
            addTaskView.showTasksList()
        }
    }

    private fun updateTask(title: String, description: String) {
        if (taskId == null) {
            //要更新的任务不存在
            throw RuntimeException("updateTask() was called but task is new.")
        }
        tasksRepository.saveTask(Task(title, description, taskId))
        addTaskView.showTasksList()
    }
}